package com.diligent.cloud.sfc.factory.impl;

import com.alibaba.fastjson.JSON;
import com.canny.commons.model.Codes;
import com.canny.commons.model.ListResult;
import com.canny.commons.model.Result;
import com.canny.commons.page.IPage;
import com.canny.commons.page.Pagination;
import com.diligent.cloud.prodbatch.model.MfgProdBatch;
import com.diligent.cloud.prodbatch.service.MfgProdBatchFeignService;
import com.diligent.cloud.sfc.factory.StationFactory;
import com.diligent.cloud.sfc.model.detail.CutDetailInfo;
import com.diligent.cloud.sfc.service.ISfcService;
import com.diligent.cloud.sfc.util.ConverterUtil;
import com.diligent.cloud.web.model.PageAndCondition;
import com.diligent.cloud.workorder.model.WoOperationCompleteDetail;
import com.diligent.cloud.workorder.model.WoOrder;
import com.diligent.cloud.workorder.service.WoOperationCompleteDetailFeignService;
import com.diligent.cloud.workordermd.feign.service.MfgConsumeDetailFeignService;
import com.diligent.cloud.workordermd.feign.service.MfgConsumeMasterFeignService;
import com.diligent.cloud.workordermd.model.MfgConsumeDetail;
import com.diligent.cloud.workordermd.model.MfgConsumeMaster;
import com.diligent.foundation.data.model.v2.Condition;
import com.google.common.base.Preconditions;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * CutStation class
 *
 * @author xf107278
 * @date 3/31/2020
 */
@Component
public class CutStation implements StationFactory {

    private ISfcService sfcService;
    private WoOperationCompleteDetailFeignService operationCompleteDetailFeignService;
    private MfgProdBatchFeignService mfgProdBatchFeignService;
    private MfgConsumeDetailFeignService consumeDetailFeignService;
    private MfgConsumeMasterFeignService consumeMasterFeignService;

    public CutStation(ISfcService sfcService,
                      WoOperationCompleteDetailFeignService operationCompleteDetailFeignService,
                      MfgProdBatchFeignService mfgProdBatchFeignService,
                      MfgConsumeDetailFeignService consumeDetailFeignService,
                      MfgConsumeMasterFeignService consumeMasterFeignService) {
        this.sfcService = sfcService;
        this.operationCompleteDetailFeignService = operationCompleteDetailFeignService;
        this.mfgProdBatchFeignService = mfgProdBatchFeignService;
        this.consumeDetailFeignService = consumeDetailFeignService;
        this.consumeMasterFeignService = consumeMasterFeignService;
    }

    @Override
    public Result getOrderInfo(WoOrder order) {
        CutDetailInfo cutDetailInfo = new CutDetailInfo();
        cutDetailInfo.setOrderLength(Long.valueOf(order.getCv4()) * order.getDeliveryDigit().longValue());
        cutDetailInfo.setRequireDigit(order.getDeliveryDigit());
        //根据工单获取生产批
        String prodBatch = getProdBatchByWoOrder(order.getWoOrder());
        //根据工单的批次查询到同批次未完成工单
        ResponseEntity<ListResult> sameOrderByProdBatch =
                sfcService.getSameOrderByProdBatch(prodBatch
                        , order.getMachineCode()
                        , order.getSystemId()
                        , order.getOrderType()
                        , 0, 0);

        cutDetailInfo.setSameBatchWaitOrder(sameOrderByProdBatch.getBody().getData().size());
        //循环未完成工单得到未剪长度
        Long waitTotalLength = 0L;
        for (LinkedHashMap orderMap : (List<LinkedHashMap>) sameOrderByProdBatch.getBody().getData()) {
            WoOrder woOrder = JSON.parseObject(JSON.toJSONString(orderMap), WoOrder.class);
            waitTotalLength =
                    waitTotalLength + (Long.valueOf(woOrder.getCv4()) * woOrder.getDeliveryDigit().longValue());
        }
        cutDetailInfo.setUndoneTotalLength(waitTotalLength);

        //根据工单的批次查询到同批次已完成工单
        sameOrderByProdBatch =
                sfcService.getSameOrderByProdBatch(prodBatch
                        , order.getMachineCode()
                        , order.getSystemId()
                        , order.getOrderType()
                        , 0, 1);
        cutDetailInfo.setSameBatchOrderCompleted(sameOrderByProdBatch.getBody().getData().size());
        //总长度 = 同批次未完成工单 + 已完成工单
        Long totalLength = 0L;
        for (LinkedHashMap orderMap : (List<LinkedHashMap>) sameOrderByProdBatch.getBody().getData()) {
            WoOrder woOrder = JSON.parseObject(JSON.toJSONString(orderMap), WoOrder.class);
            totalLength = totalLength + (Long.valueOf(woOrder.getCv4()) * woOrder.getDeliveryDigit().longValue());
        }
        cutDetailInfo.setTotalLength(totalLength + waitTotalLength);

        //获取所有同类型工单
        List<WoOrder> sameOrder = sfcService.getSameOrder(order.getMachineCode()
                , order.getOrderStatus()
                , order.getOrderType()
                , order.getSystemId()
                , order.getProduceDate());

        //同型号不同生产批等待工单
        Set<Long> sameMatCodeProdBachWaitOrder = new HashSet<>();
        //同型号不同生产批已完成工单
        Set<Long> sameMatCodeBatchOrderCompleted = new HashSet<>();
        PageAndCondition pageAndCondition = null;
        List<Condition> conditions = null;
        for (WoOrder woOrder : sameOrder) {
            //查询同型号工单
            if (order.getMatCode().equalsIgnoreCase(woOrder.getMatCode()) ) {
                //查询同型号工单且已完成挤压的工单且不同批
                pageAndCondition = new PageAndCondition();
                pageAndCondition.setPagination(new Pagination(1L, 100000L));
                conditions = new ArrayList<>();
                conditions.add(new Condition("matCode", "eq",
                        woOrder.getMatCode(), null));
                conditions.add(new Condition("endTime","nn",1,null));
                //conditions.add(new Condition("prodBatch","nin",prodBatch,null));
                pageAndCondition.setConditions(conditions);
                ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<WoOperationCompleteDetail>>>  operationCompleteDetailPage =
                        operationCompleteDetailFeignService.page(pageAndCondition);
                for (WoOperationCompleteDetail completeDetail:operationCompleteDetailPage.getBody().getData().getRecords()) {
                    if (completeDetail.getDigit()!=null){
                        sameMatCodeBatchOrderCompleted.add(completeDetail.getId());
                    }else {
                        sameMatCodeProdBachWaitOrder.add(completeDetail.getId());
                    }
                }
            }
        }
        cutDetailInfo.setSameMatCodeProdBachWaitOrder(sameMatCodeProdBachWaitOrder.size());
        cutDetailInfo.setSameMatCodeBatchOrderCompleted(sameMatCodeBatchOrderCompleted.size());

        getMouldAndDocItem(order, cutDetailInfo);
        return ConverterUtil.ConverterByData(cutDetailInfo, Codes.success.getCode(),
                Codes.success.getMsg());

    }

    private String getProdBatchByWoOrder(String woOrder) {
        PageAndCondition pageAndCondition = new PageAndCondition();
        pageAndCondition.setPagination(new Pagination(1L, 1000000000L));
        List<Condition> conditions = new ArrayList<>();
        conditions.add(new Condition("woOrder", "eq", woOrder,
                null));

//        conditions.add(new Condition("digit", "nn", 0,
//                null));
        pageAndCondition.setConditions(conditions);

        ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<WoOperationCompleteDetail>>> operationCompleteDetailPage =
                operationCompleteDetailFeignService.page(pageAndCondition);
        if (operationCompleteDetailPage.getBody().getData().getRecords().size() != 0) {
            //根据工单的批次查询到同批次未完成工单
            WoOperationCompleteDetail operationCompleteDetail =
                    operationCompleteDetailPage.getBody().getData().getRecords().stream().findFirst().get();
            return operationCompleteDetail.getProdBatch();
        } else {
            return null;
        }
    }

    private void getMouldAndDocItem(WoOrder order, CutDetailInfo cutDetailInfo) {
        String prodBach = sfcService.getProdBachByOrder(order);

        ResponseEntity<com.diligent.cloud.primary.data.model.Result> mfgProdBatchResult =
                mfgProdBatchFeignService.getByBatch(prodBach);
        if (mfgProdBatchResult.getBody().getCode() == 0) {
            ArrayList data = (ArrayList) mfgProdBatchResult.getBody().getData();
            MfgProdBatch mfgProdBatch = JSON.parseObject(JSON.toJSONString(data.stream().findFirst().get()),
                    MfgProdBatch.class);
            cutDetailInfo.setMdCode(mfgProdBatch.getCv4());
        }

        PageAndCondition pageAndCondition = new PageAndCondition();
        pageAndCondition.setPagination(new Pagination(1L, 1L));
        pageAndCondition.setConditions(Collections.singletonList(new Condition("woOrder", "eq", order.getWoOrder(),
                null)));
        ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<WoOperationCompleteDetail>>> operationCompleteDetailPage =
                operationCompleteDetailFeignService.page(pageAndCondition);
        if (operationCompleteDetailPage.getBody().getData().getRecords().size() != 0) {
            WoOperationCompleteDetail operationCompleteDetail =
                    operationCompleteDetailPage.getBody().getData().getRecords().stream().findFirst().get();

            Preconditions.checkNotNull(operationCompleteDetail.getUsrTxt1(), "工序完工单铝棒id为null");
            ResponseEntity<com.diligent.cloud.primary.data.model.Result<MfgConsumeMaster>> byId =
                    consumeMasterFeignService.getById(operationCompleteDetail.getUsrTxt1());
            Preconditions.checkNotNull(byId.getBody().getData(), "查询不到物料明细表");

            pageAndCondition.setConditions(Collections.singletonList(new Condition("masterId","eq",byId.getBody().getData().getId(),null)));
            ResponseEntity<com.diligent.cloud.primary.data.model.Result<IPage<MfgConsumeDetail>>> consumeDetailResult = consumeDetailFeignService.selectDataByConditionPage(pageAndCondition);
            if (consumeDetailResult.getBody().getData().getRecords().size()!=0){
                MfgConsumeDetail consumeDetail =
                        consumeDetailResult.getBody().getData().getRecords().stream().findFirst().get();
                cutDetailInfo.setLotCode(consumeDetail.getLotCode());

            }
        }
    }


}

